/**
 * CAgent Sidecar - Main Entry Point
 * 
 * Bun Runtime Sidecar for Claude Agent SDK Integration
 */

import { startServer } from './api/server';
import { logger } from './utils/logger';
import { config } from './utils/config';
import { initializeSubAgentManager, builtinSubAgents } from './subagents';
import { skillsManager, builtinSkills } from './skills';

/**
 * Main function
 */
async function main() {
  try {
    logger.info('🚀 Starting CAgent Sidecar...');
    logger.info(`📋 Configuration loaded`);
    logger.info(`   - Port: ${config.port}`);
    logger.info(`   - Host: ${config.host}`);
    logger.info(`   - Model: ${config.defaultModel}`);
    logger.info(`   - Max Turns: ${config.maxTurns}`);
    logger.info(`   - CORS: ${config.enableCors ? 'Enabled' : 'Disabled'}`);

    // Initialize builtin skills
    logger.info('🎨 Initializing builtin skills...');
    skillsManager.registerSkills(builtinSkills);
    logger.info(`   - Registered ${builtinSkills.length} skills`);

    // Initialize sub-agents with SkillsManager integration
    logger.info('🤖 Initializing builtin sub-agents...');
    const subAgentManager = initializeSubAgentManager(skillsManager);
    subAgentManager.registerSubAgents(builtinSubAgents);
    const stats = subAgentManager.getStats();
    logger.info(`   - Registered ${stats.total} sub-agents (${stats.builtin} builtin, ${stats.custom} custom)`);

    // Start HTTP server
    await startServer();

    logger.info('✅ CAgent Sidecar is ready!');
  } catch (error) {
    logger.error('❌ Failed to start CAgent Sidecar', error);
    process.exit(1);
  }
}

// Handle graceful shutdown
process.on('SIGINT', () => {
  logger.info('🛑 Received SIGINT, shutting down gracefully...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  logger.info('🛑 Received SIGTERM, shutting down gracefully...');
  process.exit(0);
});

// Handle uncaught errors
process.on('uncaughtException', (error) => {
  logger.error('💥 Uncaught exception', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('💥 Unhandled rejection', { reason, promise });
  process.exit(1);
});

// Start the application
main();

